package com.financing.platform.web.api;
import java.sql.SQLException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.financing.platform.dto.FaUserDTO;
import com.financing.platform.service.IUserInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IManagerLicaishiService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.vo.ManagerLicaishiVO;

@Controller("managerLicaishiActionApi")
@RequestMapping("/api/managerLicaishi")
@Scope("prototype")
public class ManagerLicaishiAction extends BaseAction {
	
	@Autowired
	IManagerLicaishiService managerLicaishiServiceImpl;

	@Autowired
	private IUserInfoService userInfoServiceImpl;

	/**
	 * 理财师权限分配
	 * @param request
	 * @param response
	 * @param managerLicaishi
	 * @param LicaishiIds 
	 * @return
	 */
	@RequestMapping("/addManagerLicaishiUser.shtml")
	@ResponseBody
	public synchronized ResultMap addManagerLicaishiUser(HttpServletRequest request, HttpServletResponse response,
			ManagerLicaishiVO managerLicaishiVo) {
		if(StringUtils.isBlank(managerLicaishiVo.getLicaishiIds())||StringUtils.isBlank(managerLicaishiVo.getSystemUserId())){
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
			return resultMap;
		}
		int count=0;
		try {
			HttpSession session = request.getSession();
			UserInfoDTO user = (UserInfoDTO)session.getAttribute(DTOdateSet.user);
			//

			//单个内部理财师OK类客户数量限制为50个，达到50个就不能再接受分配；
			//单个内部理财师A类客户数量限制为300个，达到300个就不能再接受分配
			resultMap.setAttribute("map",checkManagerLicaishi(managerLicaishiVo));

			if(StringUtils.isBlank(managerLicaishiVo.getLicaishiIds())){
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
				return resultMap;
			}

			//先回收
			ManagerLicaishiVO managerLicaishi = new ManagerLicaishiVO();
			managerLicaishi.setLicaishiIds(managerLicaishiVo.getLicaishiIds());
			managerLicaishiServiceImpl.editManagerLicaishiByUser(managerLicaishi,user);
			count = managerLicaishiServiceImpl.batchAddManagerLicaishiUser(managerLicaishiVo,user);
		} catch (SQLException e) {
			log.error("batchAddManagerLicaishiUser error",e);
		}
		if (count > 0) {
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} else {
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	private Map<String,Integer> checkManagerLicaishi(ManagerLicaishiVO managerLicaishiVo) throws SQLException {

		//当前登录用户的用户访问详情
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("systemUserId", managerLicaishiVo.getSystemUserId());
		map.put("sysUserId", "self");//查询自己
		List<Map<String, Object>> current = userInfoServiceImpl.queryVistDetail(map);
		Map<String, Object> reMap = (current != null && current.size() > 0) ? current.get(0) : new HashMap<String, Object>();
		Integer okCount = reMap.containsKey("okcountRate") ? Integer.valueOf(reMap.get("okcountRate").toString()) : 0;
		Integer aCount = reMap.containsKey("acountRate") ? Integer.valueOf(reMap.get("acountRate").toString()) : 0;
		Integer not_okCount = 0;
		Integer not_aCount = 0;

		FaUserDTO faUserDTO = new FaUserDTO();
		faUserDTO.setLicaishiIds(managerLicaishiVo.getLicaishiIds());
		List<FaUserDTO> list = faUserServiceImpl.queryAllFaUserInfoBasic(faUserDTO);
		Set set = new HashSet();
		for (FaUserDTO bean:list){
			if("OK".equals(bean.getuSystemRate())){
				if(okCount <  50){
					set.add(bean.getId().toString());
					okCount ++ ;
				}else{
					not_okCount ++;
				}
			}else if("A".equals(bean.getuSystemRate())){
				if(aCount <  300){
					set.add(bean.getId().toString());
					aCount ++ ;
				}else{
					not_aCount ++;
				}
			}else{
				set.add(bean.getId().toString());
			}
		}
		String[] licaishiIdGroup = (String [])set.toArray(new String[0]);
		String a = StringUtils.join(licaishiIdGroup, ",");
		managerLicaishiVo.setLicaishiIds(a);
		Map<String,Integer> remap = new HashMap<String, Integer>();
		remap.put("not_okCount",not_okCount);
		remap.put("not_aCount",not_aCount);

		return remap;

	}

	/**
	 * 回收理财师管理员下的所有理财师
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/editManagerLicaishiByUser.shtml")
	@ResponseBody
	public ResultMap editManagerLicaishiByUser(HttpServletRequest request, HttpServletResponse response,ManagerLicaishiVO managerLicaishiVo) {
		try {

			if(StringUtils.isBlank(managerLicaishiVo.getLicaishiIds())&&StringUtils.isBlank(managerLicaishiVo.getSystemUserId())){
				resultMap.setStatus(STATUS.ERROR);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}

			HttpSession session = request.getSession();
			UserInfoDTO user = (UserInfoDTO)session.getAttribute(DTOdateSet.user);

			//获取用户的-名单共有池
			String publicLicaishi = null;
			UserInfoDTO  loginInfo =  new UserInfoDTO();
			loginInfo.setUserId(user.getUserId());
			loginInfo = userInfoServiceImpl.queryUserInfo(loginInfo);
			publicLicaishi = getPublicLicaishi(loginInfo);

			//先回收
			ManagerLicaishiVO managerLicaishi = new ManagerLicaishiVO();
			managerLicaishi.setLicaishiIds(managerLicaishiVo.getLicaishiIds());
			int count = managerLicaishiServiceImpl.editManagerLicaishiByUser(managerLicaishi,user);

			if(StringUtils.isNotBlank(publicLicaishi)) {
				managerLicaishiVo.setSystemUserId(publicLicaishi);
				managerLicaishiServiceImpl.batchAddManagerLicaishiUser(managerLicaishiVo, user);
			}

			if (count > 0) {
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			} else {
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}

		} catch (Exception e) {
			log.error("editManagerOrderByUser error", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	private String getPublicLicaishi(UserInfoDTO loginInfo) {
		if(loginInfo == null){
			return null;
		}
		if(StringUtils.isNotBlank(loginInfo.getPublicDeptHead())){
			return loginInfo.getPublicDeptHead();
		}
		if(StringUtils.isNotBlank(loginInfo.getParentUserId())){
			UserInfoDTO  parentUser =  new UserInfoDTO();
			parentUser.setUserId(loginInfo.getParentUserId());
			parentUser = userInfoServiceImpl.queryUserInfo(parentUser);
			return getPublicLicaishi(parentUser);
		}else{
			return null;
		}

	}

}
